package com.ngc.mall.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ngc.mall.common.configure.exception.BusinessException;
import com.ngc.mall.core.enumeration.ActivityStatus;
import com.ngc.mall.domain.LotteryRecordDomain;
import com.ngc.mall.mapper.LotteryRecordMapper;
import com.ngc.mall.service.ILotteryRecordService;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 *
 * 抽奖大转盘实现类
 * @author: chenxiaolin
 * @date 2023/10/16 9:49
**/
@Service
public class LotteryRecordServiceImpl extends ServiceImpl<LotteryRecordMapper, LotteryRecordDomain> implements ILotteryRecordService {

    @Override
    public List<LotteryRecordDomain> findMyLotteryRecords(Long uid){
        LocalDateTime now=LocalDateTime.now();
        List<LotteryRecordDomain> list=super.list(Wrappers.<LotteryRecordDomain>lambdaQuery().eq(LotteryRecordDomain::getUserId,uid).orderByDesc(LotteryRecordDomain::getCreateTime));
        for(LotteryRecordDomain domain:list){
            int status= checkStatus(now,domain.getCreateTime(),domain.getExpireTime());
            if(domain.getStatus()!=status){
                domain.setStatus(status);
                super.updateById(domain);
            }
        }
        return list;
    }
    public int checkStatus(LocalDateTime now,LocalDateTime start,LocalDateTime end){
        if (now.isAfter(start) && now.isBefore(end)) {
            return ActivityStatus.DOING.getValue();
        } else if (now.isBefore(start)) {
            return ActivityStatus.PENDING.getValue();
        } else if (now.isAfter(end)) {
            return ActivityStatus.COMPLETED.getValue();
        } else {
            throw BusinessException.FAILURE;
        }
    }
    @Override
    public List<LotteryRecordDomain> selectAll(){
        return super.list(Wrappers.<LotteryRecordDomain>lambdaQuery().orderByDesc(LotteryRecordDomain::getCreateTime));
    }

    @Override
    public List<LotteryRecordDomain> findByLotteryId(Long lotteryId){
        return super.list(Wrappers.<LotteryRecordDomain>lambdaQuery().eq(LotteryRecordDomain::getLotteryId,lotteryId).orderByDesc(LotteryRecordDomain::getCreateTime));
    }
}
